<?php
// +----------------------------------------------------------------------
// | Description: 消费流水 - Bill
// +----------------------------------------------------------------------
// | Author: liaoyizhi <liaoyizhi@gmail.com>
// +----------------------------------------------------------------------
// | Update: Markus <i@yoyoyo.me>
// +----------------------------------------------------------------------

namespace codelord\finance\model;

use think\Model;
use think\Exception;
use think\Paginator;

class Bill extends Model {
    /**
     * 获取用户交易记录
     * @param array $param
     * @param int $uid
     * @return null|Paginator
     */
    public function getBillList(array $param,int $uid) : ? Paginator
    {
        $query = ['query'=>['a.uid'=>$uid],'page'=>$param['page']];

        $join = [
            ['bill_type b','a.bill_type_id = b.id','LEFT'],
            ['currency c','a.currency_id = c.id','LEFT']
        ];

        $data = $this->alias('a')
            ->where(['a.uid'=>$uid])
            ->join($join)
            ->field('b.name as bill_type,c.name as currency,a.amount,a.add_time,a.op_reason')
            ->order('a.add_time desc')
            ->paginate($param['rows'], false, $query);

        return $data;
    }

    /**
     * 插入bill表，记录消费流水
     * @param array $currency_data  各种货币消费组装数组
     * @param array $user_balance   用户当前余额数组
     * @throws Exception
     */
    public function insertBill(array $currency_data,array $user_balance) : void
    {
        $data = [];
        foreach ($currency_data['currency'] as $currency) {
            //if (abs($currency[1]) > 0 || abs($currency[2]) > 0) { //大于0 的生成记录
            $data[] = [
                    'uid' => $currency_data['uid'],
                    'bill_type_id' => $currency_data['bill_type_id'],
                    'currency_id' => $currency[0],
                    'number' => $currency_data['number'],
                    'amount' => $currency[1],
                    'amount_lock' => $currency[2],
                    'amount_balance' => $user_balance[$currency[0]]['amount'],
                    'amount_lock_balance' => $user_balance[$currency[0]]['amount_lock'],
                    'add_time' => time(),
                    'op_person' => $currency_data['op_person'],
                    'op_reason' => $currency[3]
                ];
            //}
        }
        $check = $this->insertAll($data);

        if (!$check) {
            throw new Exception('写入bill记录失败', 20004);
        }
    }
}
